<?php
/**
 * Небольшой скриптик имитирующий Wayfinder и одну опцию к нему hideSubMenus
 *
 * Скрипт небольшой но с возможностью дальнейшего наращивания
 *
 * @author tonatos
 */
class wayfinder_mode {

    //Менять этот параметр true|false
    public $hideSubMenus = true;

    public function __construct($sMode = false, $toPlaceholder = true, $iCatId = false) {
        global $modx;

        $this->allowids = array();
        
        if ($toPlaceholder) {
            $modx->setPlaceholder('sb.wayfinder', $this->execute());
        }
    }

    public function execute() {
        global $modx;

        $tree = new SBCatTree();
        $rows = $tree->getCategories();
        $this->m_tree = array();

        $this->current_category = $modx->sbshop->oGeneralCategory;

        if ($this->hideSubMenus) {
            $this->allowids = explode(".", $this->current_category->getAttribute("path"));
        }

        //Делаем нормальное дерево
        foreach ($rows as $row) {
            if ($row->getAttribute("level") == 0) {
                $this->parse_tree($rows, $row);
                $this->m_tree[$row->getAttribute('id')] = $row;
            }
        }

        return $this->output_tree($this->m_tree);
    }

    public function parse_tree($data, $parent) {

        if ($this->hideSubMenus){
            if (!in_array($parent->getAttribute("id"), $this->allowids)) {
                return;
            }
        }
        $parent->childs = array();
        foreach ($data as $row) {
            if ($row->getAttribute("parent") == $parent->getAttribute("id")) {
                $parent->childs[$row->getAttribute("id")] = $row;
                $this->parse_tree($data, $row);
            }
        }
    }

    public function output_tree($nodes) {
        global $modx;

        if (empty($nodes)){
            return "";
        }
        $result = "<ul>";

        foreach ($nodes as $node) {
            $aRepl = $modx->sbshop->arrayToPlaceholders($node->getAttributes());

            $class = (($this->current_category) && ($this->current_category->getAttribute("id")==$node->getAttribute("id"))) ? 'active':'';
            
            $result .="<li><a class='$class' href='" . $aRepl['[+sb.url+]'] . "'>" . $aRepl['[+sb.title+]'] . "</a>";
            $result .= $this->output_tree($node->childs);
            $result .= "</li>";
        }

        $result .= "</ul>";

        return $result;
    }

}

?>
